package com.bainuo.doctor.common.util;

import android.app.Activity;
import android.content.Context;
import android.graphics.Rect;
import android.os.Build;
import android.os.Handler;
import android.support.annotation.RequiresApi;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;

import java.lang.reflect.Field;

/**
 * Created by SeenFar on 16/6/21.
 */
public class KeyBoardManager {


    public View mRootView;
    public int mScreenHeight;
    public int mDelay = 300;
    private int maxBottom;
    public boolean isShow;

    private ViewTreeObserver.OnGlobalLayoutListener layoutListener;

    private KeyboardListener listener;

    public interface KeyboardListener {

        void onKeyboardShow(int keyBoardHeight);

        void onKeyboardHiden(int keyBoardHeight);

    }

    public void setKeyboardListener(KeyboardListener listener) {
        this.listener = listener;
    }


    public void setRootView(Activity activity) {

        Window window = activity.getWindow();
        if (window == null)
            return;

        window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        ViewGroup vg = (ViewGroup) window.getDecorView();
        if (vg != null) {
            View view = vg.getChildAt(0);
            setRootView(view);
        }

        mScreenHeight = activity.getWindowManager().getDefaultDisplay().getHeight();

    }


    public void setRootView(View view) {
        if (view == null)
            return;

        mRootView = view;


        layoutListener = new ViewTreeObserver.OnGlobalLayoutListener() {

            @Override
            public void onGlobalLayout() {


                final Rect r = new Rect();
                mRootView.getWindowVisibleDisplayFrame(r);

                // LogUtil.i("KeyBoardManager", "keybou-->" + r.bottom);

                if (maxBottom == 0) {
                    maxBottom = r.bottom;
                }

                if (r.bottom < maxBottom && !isShow) {

                    isShow = true;
                    if (listener != null) {
                        listener.onKeyboardShow(maxBottom - r.bottom);
                    }

                }


                if (r.bottom == maxBottom && isShow) {
                    isShow = false;

                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {

                            mRootView.getWindowVisibleDisplayFrame(r);
                            if (listener != null && r.bottom == maxBottom) {
                                listener.onKeyboardHiden(maxBottom - r.bottom);
                            }
                        }
                    }, mDelay);
                }
            }
        };

        view.getViewTreeObserver().addOnGlobalLayoutListener(layoutListener);
    }

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    public void removeRootView() {
        mRootView.getViewTreeObserver().removeOnGlobalLayoutListener(layoutListener);
    }


    public void adjuctView(View view, int bottomMargin, int kh) {

        adjuctView(mRootView, view, bottomMargin, kh);
    }

    public void adjuctView(View rootView, View view, int bottomMargin, int kh) {

        int vb = ViewUtil.getLocation(view).bottom;
        Rect rt = ViewUtil.getLocation(rootView);
        int rb = rt.bottom;


        int b = kh - (rb - vb);
        int y = mScreenHeight - rootView.getHeight() - b;

        int currentY = (int) rootView.getY();
        int offsetY = rt.top - currentY;

        y -= (bottomMargin + offsetY);
        if (y < currentY) {
            rootView.setY(y);

//            Animation animation = new TranslateAnimation(0,0,0,currentY - y);

//            Animation animation =
//                    new TranslateAnimation(Animation.RELATIVE_TO_PARENT, 0,
//                            Animation.RELATIVE_TO_SELF, 0,
//                            Animation.ABSOLUTE, 0
//                            , Animation.ABSOLUTE, y-currentY);
//            animation.setDuration(300);
////            animation.setFillAfter(true);
//            rootView.setAnimation(animation);
        }


    }


    public void recoveryView() {
        mRootView.setY(maxBottom - mRootView.getHeight());

    }


    public static void setKeyBoardState(View v, boolean state) {

        if (state == true) {

            v.requestFocus();
            InputMethodManager inputManager =
                    (InputMethodManager) v.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
            inputManager.showSoftInput(v, 0);

            inputManager.toggleSoftInput(InputMethodManager.SHOW_FORCED,
                    InputMethodManager.HIDE_IMPLICIT_ONLY);

        } else {


            InputMethodManager inputManager =
                    (InputMethodManager) v.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
            inputManager.showSoftInput(v, 0);
            inputManager.hideSoftInputFromWindow(
                    v.getApplicationWindowToken(), 0);

        }

    }

    /**
     * 是否键盘打开
     * @param context
     * @param rootViewHeight
     * @return
     */
    public static boolean isSoftInputOpen(Activity context, int rootViewHeight) {
        int screenHeight = context.getWindowManager().getDefaultDisplay().getHeight() - getStatusHeight(context);
        // 键盘打开状态
        return rootViewHeight > 0 && rootViewHeight < screenHeight;
    }


    // 获取状态栏高度
    public static int getStatusHeight(Context context) {
        Class<?> c = null;
        Object obj = null;
        Field field = null;
        int x = 0, barHeight = 0;
        try {
            c = Class.forName("com.android.internal.R$dimen");
            obj = c.newInstance();
            field = c.getField("status_bar_height");
            x = Integer.parseInt(field.get(obj).toString());
            barHeight = context.getResources().getDimensionPixelSize(x);
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        return barHeight;
    }

    /**
     * 隐藏键盘
     *
     * @param editText
     * @param context
     */
    public static void hideSoftKeyboard(View editText, Context context) {
        if (editText != null && context != null) {
            InputMethodManager imm = (InputMethodManager) context
                    .getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);
        }
    }

}
